package com.test.base.netty.createserver;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

@Slf4j
public class EventLoopServer2 {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup(2);

        ChannelFuture channelFuture = new ServerBootstrap()
                // 设置两个，一个用于Accept，一个用于处理READ和WRITE
                .group(new NioEventLoopGroup(2), new NioEventLoopGroup(2))
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                // 不指定字符集的结果：PooledUnsafeDirectByteBuf(ridx: 0, widx: 11, cap: 2048)
//                                log.debug(buf.toString());
                                log.debug(buf.toString(Charset.defaultCharset()));
                            }
                        });
                        ch.pipeline().addLast(group, new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                ByteBuf buf = (ByteBuf) msg;
                                log.debug(buf.toString(Charset.defaultCharset()));
                            }
                        });
                    }
                })
                .bind(8080);
    }
}
